#!/usr/bin/env bash
# shellcheck disable=SC2086
# shellcheck disable=SC2009
# shellcheck disable=SC2002
# shellcheck disable=SC2143
# shellcheck disable=SC2116
# shellcheck disable=SC2207

{
    {
        _pak_path="/usr/bin/sensors"
        if [[ ! -f "$_pak_path" ]]; then
            apt update &>/dev/null
            apt-get install -y lm-sensors &>/dev/null
        fi
    }

    {
        current_time=$(date +"%T")
        echo -e "\033[33m=== Ubuntu POP Check t241122 ===\033[32m\nUpdate Time: 2024-11-22\n\033[32mCurrent Time: $current_time\nAdaptation system: Ubuntu LTS\033[0m"
        echo -e "\033[33m温馨提示:\n此脚本为业务检查脚本,可重复执行,没有任何影响!\n刚部署上机的设备请耐心等待程序启动!\n新设备上机没有流量属于正常现象,请不要担心,有了缓存才会有速度!\n缓存凌晨下载,白天不定时下载!\n"
    }

    {
        {
            # 查看系统
            hostnamectl=$(hostnamectl | awk '/Operating System/ {print $3 " "$5}')
            if [[ $hostnamectl != "Ubuntu LTS" ]]; then
                echo "未检测适配系统"
                exit
            else
                echo -e "\033[36m系统:\033[0m $hostnamectl"
            fi
        }

        {
            # 查内核版本
            echo -e "\033[36m内核版本:\033[0m $(uname -r)"
        }

        {
            # 检查温度文件是否存在
            if [ -f /sys/class/thermal/thermal_zone0/temp ]; then
                cpu_temp=$(cat /sys/class/thermal/thermal_zone0/temp)
                cpu_sensors=$(echo $((cpu_temp / 1000))°)                               # 温度转换为°C
            else
                cpu_sensors="N/A"                                                       # 如果文件不存在，设置为N/A
            fi
            echo -e "\033[36mCPU 温度:\033[0m $cpu_sensors"
        }

        {
            # 检查内存占用率
            total_mem=$(free -g | awk '/Mem:/ {print $2}')  # 总内存
            used_mem=$(free -g | awk '/Mem:/ {print $3}')   # 已用内存
            memory_usage=$(echo "scale=2; $used_mem / $total_mem * 100" | bc)

            # echo -e "\033[36m总内存:\033[0m $total_mem  GB"
            # echo -e "\033[36m已用内存:\033[0m $used_mem GB"
            echo -e "\033[36m内存占用率: \033[0m$memory_usage%"
        }
    }

    {
        # 检查zabbix ID和suid
        {
            ubuntu_suid="$(cat /data/kuaicdn/labels/suid)"
            if [[ -z $ubuntu_suid ]]; then
                echo -e "\033[36mUbuntu suid:\033[0m suid不存在         \033[31m...ERROR\033[0m"
            else
                echo -e "\033[36mUbuntu suid:\033[0m ${ubuntu_suid:-none}"
            fi
        }

        {
            zabbix_id="$(cat /data/kuaicdn/conf/label/device_id 2>/dev/null)"
            if [[ $zabbix_id ]]; then
                echo -e "\033[36mZABBIX ID:\033[0m ${zabbix_id:-none}"
            fi
        }
    }

    {
        # 查是否挂盘
        disk_list="$(lsblk | grep '/disk/[0-9a-z]{8}' -Eo)"
        if [ -z "$disk_list" ]; then
            echo -e "\033[36m磁盘:\033[0m 未挂载         \033[31m...ERROR\033[0m"
        else
            echo -e "\033[36m磁盘:\033[0m 已挂盘         \033[32m...OK\033[0m"
        fi
    }

    {
        # 检查镜像版本
        if [[ -n "$(grep blm /etc/blos.conf 2>/dev/null)" ]]; then
            echo -e "\033[36m镜像版本:\033[0m 菠萝蜜专用镜像"
        elif [[ -n "$(grep mht /etc/blos.conf 2>/dev/null)" ]]; then
            echo -e "\033[36m镜像版本:\033[0m 猕猴桃专用镜像"
        elif [[ -n "$(grep none /etc/blos.conf 2>/dev/null)" ]]; then
            echo -e "\033[36m镜像版本:\033[0m 通用镜像"
        elif [[ $(pgrep -f 'bbiz-os-blm-t2407280' -c) == "1" ]]; then
            echo -e "\033[36m镜像版本:\033[0m 菠萝蜜专用镜像"
        elif [[ $(pgrep -f 'bbiz-os-mht-t2407280' -c) == "1" ]]; then
            echo -e "\033[36m镜像版本:\033[0m 猕猴桃专用镜像"
        else
            echo -e "\033[36m镜像版本:\033[0m 通用镜像"
        fi
    }

    {
        {
            # 检查是否出省
            _pop_config=$(cat /data/kuaicdn/bbiz/pop/config.conf 2>/dev/null)
            if [[ -z $_pop_config ]]; then
                echo -e "\033[36m是否出省:\033[0m 全国调度"
            elif [[ $(cat /data/kuaicdn/bbiz/pop/config.conf | grep "dispatch_mode=0" 2>/dev/null) ]]; then
                echo -e "\033[36m是否出省:\033[0m 全国调度"
            elif [[ $(cat /data/kuaicdn/bbiz/pop/config.conf | grep "dispatch_mode=1" 2>/dev/null) ]]; then
                echo -e "\033[36m是否出省:\033[0m 省内同运营商"
            elif [[ $(cat /data/kuaicdn/bbiz/pop/config.conf | grep "dispatch_mode=2" 2>/dev/null) ]]; then
                echo -e "\033[36m是否出省:\033[0m 省内跨运营商"
            elif [[ $(cat /data/kuaicdn/bbiz/pop/config.conf | grep "dispatch_mode=5" 2>/dev/null) ]]; then
                echo -e "\033[36m是否出省:\033[0m 异网调度"
            else
                echo -e "\033[36m是否出省:\033[0m 未知"
            fi
        }

        {
            _speed_max=$(awk -F'=' '/network_max_bw/ {print $2}' /data/kuaicdn/bbiz/pop/config.conf)
            echo -e "\033[36m单线大小:\033[0m ${_speed_max:-none}"
        }

        # 检查容器是否通网
        {
            _pop_mode="biz-pop-client-t2407080|bbiz-os-blm-t2407280|jcsj-os-blm-t2407280|bbiz-pop-roll-t2409070|bbiz-pop-roll-t241122"
            _bbiz_pop="$(docker ps -a 2>/dev/null | grep Up | grep -Eo "$_pop_mode")"
            _bbiz_pop_status="$(docker ps -a --format "table {{.Names}}\t{{.Status}}" | grep -E "$_pop_mode" | awk '{print $2}')"
            _biz_pop_network=$(timeout 3 docker exec $_bbiz_pop bash -c "curl -s cip.cc" 2>/dev/null)
            if [[ -z $_bbiz_pop ]]; then
                echo -e "\033[36m管理容器:\033[0m 容器不存在     \033[31m...ERROR\033[0m"
                if [[ -z $_bbiz_pop_status ]]; then
                    echo -e "\033[36m管理容器:\033[0m $_bbiz_pop      \033[31m...ERROR\033[0m"
                else
                    echo -e "\033[36m管理容器:\033[0m ${_bbiz_pop:-none}         \033[32m...OK\033[0m"
                fi
            else
                if [[ "$_bbiz_pop_status" != "Up" ]] || [[ -z $_biz_pop_network ]]; then
                        echo -e "\033[36m管理容器:\033[0m $_bbiz_pop      \033[31m...ERROR\033[0m"
                    else
                        echo -e "\033[36m管理容器:\033[0m $_bbiz_pop      \033[32m...OK\033[0m"
                fi
            fi
        }

        {
            _node_pop_list=($(docker ps -a --format "{{.Names}}" | grep node-pop-))
            if [ ${#_node_pop_list[@]} -eq 0 ]; then
                echo -e "\033[36m业务容器:\033[0m 容器不存在     \033[31m...ERROR\033[0m"
                return 0
            fi

            # 随机选择一个容器
            random_index=$((RANDOM % ${#_node_pop_list[@]}))
            _random_node_pop=${_node_pop_list[$random_index]}

            status=$(docker inspect --format='{{.State.Status}}' "$_random_node_pop")
            network=$(timeout 3 docker exec "$_random_node_pop" bash -c "curl -s cip.cc" 2>/dev/null)

            if [[ -z $status ]] || [[ -z $network ]]; then
                echo -e "\033[36m业务容器:\033[0m $_random_node_pop     \033[31m...ERROR\033[0m"
            else
                if [[ "$status" != "running" ]]; then
                    echo -e "\033[36m业务容器:\033[0m $_random_node_pop     \033[31m...ERROR\033[0m"
                else
                    # 运行 PoPMachine 检查
                    docker exec "$_random_node_pop" bash -c '
                    {
                        start_time=$(ps -o lstart= -p $(pgrep PoPMachine))
                        if [ -z "$start_time" ]; then
                            echo "未找到 PoPMachine 进程"
                            exit 1
                        fi
                        start_timestamp=$(date -d "$start_time" +%s)
                        current_timestamp=$(date +%s)
                        time_diff=$((current_timestamp - start_timestamp))
                        if [ "$time_diff" -gt 180 ]; then
                            echo -e "\033[36m业务容器:\033[0m '"$_random_node_pop"'     \033[32m...OK\033[0m"
                        elif [ "$time_diff" -gt 120 ]; then
                            echo -e "\033[36m业务容器:\033[0m '"$_random_node_pop"'     \033[33m...wait\033[0m"
                        else
                            echo -e "\033[36m业务容器:\033[0m '"$_random_node_pop"' 网络不支持, 路由拨号请设置DMZ, 光猫DHCP请在光猫开启DMZ; 或者光猫改桥接直接服务器拨号      \033[33m...To be optimization\033[0m"
                        fi
                    }'
                fi
            fi
        }

        {
            # 检查接口类型
            if [[ "$(ip -br a | grep '^ppp[0-9a-z]{12}' -Ec)" != "0" ]]; then
                default_interface=$(ip route | awk '/default/ {print $3; exit}')
            elif [[ "$(ip -br a | grep '^m-ss-[0-9a-z]' -Ec)" != "0" ]]; then
                default_interface=$(ip route | awk '/default/ {print $5; exit}')
            else
                default_interface=$(ip route | awk '/default/ {print $5; exit}')
            fi
            dail_net="$(timeout 3 curl --interface $default_interface -s myip.ipip.net 2>/dev/null)"
            echo -e "\033[36m拨号网络:\033[0m  ${dail_net:-none}"
        }
    }

    {
        # 进程检查待优化
        PoPMachine=$(ps -ef | grep -v grep | grep -Ec "PoPMachine")
        if [[ $PoPMachine -eq 0 ]]; then
            echo -e "\033[36mPoP进程数量:\033[0m $PoPMachine        \033[31m...ERROR\033[0m"
        else
            echo -e "\033[36mPoP进程数量:\033[0m $PoPMachine        \033[32m...OK\033[0m"
        fi
    }

    {
        # 单盘实例检查
        disk_list="$(lsblk | grep '/disk/[0-9a-z]{8}' -Eo)"
        echo -e "\033[36m磁盘容量:\033[0m"
        for item in ${disk_list}; do
            # 检查磁盘是否可访问
            if [ ! -d "$item" ]; then
                echo -e "$item:    磁盘异常        \033[31m...ERROR\033[0m"
                continue
            fi

            cache_number=$(find $item/cache-bcdn -maxdepth 1 -mindepth 1 -type d 2>/dev/null | grep -Ec "[0-9]{3}")
            cache=$(du -sh ${item}/cache-bcdn 2>/dev/null | awk '{print $1}')

            # 检查缓存目录是否存在
            if [ -z "$cache" ]; then
                echo -e "$item/cache-bcdn:    缓存目录不存在        \033[31m...ERROR\033[0m"
                continue
            fi

            # 计算单独一个磁盘目录占用百分比
            cache_size=$(du -s ${item}/cache-bcdn 2>/dev/null | cut -f1)
            disk_space=$(df -k $item | awk 'NR==2 {print $2}')

            # 检查磁盘空间是否可用
            if [ -z "$disk_space" ] || [ "$disk_space" -eq 0 ]; then
                echo -e "$item:    磁盘空间无法获取        \033[31m...ERROR\033[0m"
                continue
            fi

            percentage=$((cache_size * 100 / disk_space))
            printf "%s     目录数量: %02d     容量: %s     缓存占比: %d%% \n" "$item" "$cache_number" "$cache" "$percentage"
        done
    }

    {
        {
            # 拨号网络检查
            _ppp_accounts=$(curl -sSL -X GET http://127.0.0.1:41100/api/v2/network/pppoe/crud | jq 2>/dev/null)
            _ppp_net_data=$(echo "$_ppp_accounts" | jq -r '.data[] | [ .uuid, .enable, .username, .password, .pnic, .vlan, .upload, .download, .mac] | @tsv')
            if [[ -n $_ppp_net_data ]]; then
                curl -fsSL https://1142.s.kuaicdn.cn:11428/dong/shell/raw/branch/main/ubuntu/network/dial/t240831/state.sh | bash
            fi
        }

        {
            _static_accounts=$(curl -s -X GET http://127.0.0.1:41100/api/v2/network/static/crud | jq 2>/dev/null)
            _static_net_data=$(echo "$_static_accounts" | jq -r '.data[] | [ .uuid, .enable, .ip_mask, .gateway, .pnic, .vlan, .upload, .download, .mac] | @tsv')
            if [[ -n $_static_net_data ]]; then
                curl -fsSL https://1142.s.kuaicdn.cn:11428/dong/shell/raw/branch/main/ubuntu/network/dial/t240831/static_state.sh | bash
            fi
        }
    }
}





__help() {
  cat >/dev/null <<-'AEOF'

curl -fsSL https://1142.s.kuaicdn.cn:11428/dong/shell/raw/branch/main/ubuntu/pop/inspect/t241122/check.sh | bash

AEOF
}